package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000243.R;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.IoTaskProgress;
import com.shwread.httpsdk.http.download.DownloadForProgressAction;
import com.tgx.tina.android.task.ATaskService;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.json.JSONException;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import base.tina.core.task.infc.ITaskProgress.TaskProgressType;
import logic.bean.BookBean;
import logic.bean.BookInfo;
import logic.bean.ChapterInfo;
import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.beanenum.BookType_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.FileUtil;
import logic.util.SDcardUtil;
import logic.util.Util;
import logic.util.Utils;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * 在线目录页面
 */
public class CatalogActivity extends BaseBusinessActivity implements OnClickListener {
    private TextView tvTitle;
    private Button btnBack;
    private ListView lv;

    private BookInfo bookInfo;
    private int bookStatus = 2;

    private List<TOCItem> catalogList;
    private List<String> dirctorys;

    private Adapter myAdapter;

    private Context context;
    private BookDao bookDao;

    //	private AddShelfBookAction addShelfBookAction;
    String path;
    int mPosition;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    initDirctory();
                    myAdapter.notifyDataSetChanged();
                    break;
                case 101:
                    openBook(path, mPosition);
                    break;
                case 102:
                    Bundle bundle = msg.getData();
                    Util.showToast(context, bundle.getString("message"));
                    break;
                case DefaultConsts.UPDATEUI_BOOKSHELF_BOOKS_OK:
                    openBook(path, mPosition);
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        bookDao = BookDao.getInstance(this);
        mAService = new ATaskService();
        mAService.startAService(this);
        //		addShelfBookAction = new AddShelfBookAction(this);
        initData();
        findViews();
    }

    @Override
    protected void onDestroy() {
        if (mAService != null) {
            mAService.stopAService();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeLoading();
    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    private void findViews() {
        setContentView(R.layout.catalog);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("目录");
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        lv = (ListView) findViewById(R.id.catalog_listview);
        lv.setAdapter(myAdapter);
        lv.setOnItemClickListener(new ListViewItemClick());
    }

    void addBooktoShelf(int status) {
        bookDao.addBooktoShelf(toBookBean(status, bookInfo));
    }

    private BookBean toBookBean(int status, BookInfo bean) {
        String path = "";
        if (status == BookStatus_Enum.DOWNLOAD.getValue()) {
            path = FileUtil.DownloadPath() + String.valueOf(bean.getBookId()) + ".ceb";
        } else if (status == BookStatus_Enum.ONLINE.getValue()) {
            path = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + "toc.ncx";
        }
        if ("1".equals(bean.getBookType())) {
            bean.setContent_type("6");
        }
        BookBean bookbean = new BookBean(status, bean.getBookId(), bean.getName(), Integer.parseInt(bean.getContent_type()), 0, path, bean.getAuthor(), Const.phone_number, String.valueOf(System.currentTimeMillis()), bean.getLogoUrl());
        return bookbean;
    }

    private class ListViewItemClick implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
            if (!SDcardUtil.isSDCARDMounted()) {
                Util.showToast(context, context.getResources().getString(R.string.image_save_sdcard_deny));
                return;
            }
            if (bookStatus == 3) {//离线阅读
                showLoading();
                Intent intent = new Intent(context, ReadingBookActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(ReadingBookActivity.BOOKSTATUS, BookStatus_Enum.DOWNLOAD.getValue());
                intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bookInfo.getBookId()));
                intent.putExtra(DefaultConsts.chapterId_index_i, position);
                intent.putExtra(DefaultConsts.book_name, bookInfo.getName());
                path = FileUtil.DownloadPath() + bookInfo.getBookId() + ".ceb";
                Uri url = Uri.parse(path);
                intent.setData(url);
                intent.putExtra("IsFromCatalogActivity", true);
                startActivity(intent);
                QyreaderPerferencesUtil.getInstance(context, Const.phone_number).setLocalIndex(String.valueOf(bookInfo.getBookId()), position);
            } else {
                NewActionHelp.qryChapterInfo(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position).getId(), new ObjectHttpResponseHandler<ChapterInfo>() {

                    @Override
                    public Type getType() {
                        return new TypeToken<ChapterInfo>() {
                        }.getType();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
                        if (statusCode == 6201 || statusCode == 6202) {
                            try {
                                Utils.showToast(context, JSONUtil.getString(responseString));
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            return;
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
                        path = FileUtil.OnlinePath(String.valueOf(bookInfo.getBookId()));
                        if (BookType_Enum.MAGAZINE.getValue().equals(bookInfo.getContent_type()) && BookType_Enum.MAGAZINE.getValue().equals(bookInfo.getBookType())) {
                            showLoading();
                            if (FileUtil.FileExist(String.valueOf(bookInfo.getBookId()), catalogList.get(position).getId() + ".html")) {
                                openBook(path, position);
                            } else {
                                mPosition = position;
                                //						new QryChapterInfoAction(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position).getId(), new ChapterInfoListener()).start();
                                new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position).getId(), new ChapterInfoHandler());
                            }
                        } else {
                            openBook(path, position);
                        }
                    }
                });
            }
        }
    }

    void openBook(String path, int position) {
        addBooktoShelf(2);
        if (BookType_Enum.MAGAZINE.getValue().equals(bookInfo.getContent_type()) && BookType_Enum.MAGAZINE.getValue().equals(bookInfo.getBookType())) {
            BookBean markBean = new BookBean();
            markBean.book_id = bookInfo.getBookId();
            markBean.book_name = bookInfo.getName();
            markBean.book_type = 2;
            Intent intent = new Intent(this, ReadingmagazineActivity.class);
            //			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("BookMarkBean", markBean);
            intent.putExtra(DefaultConsts.chapterId_index_i, position);
            startActivity(intent);
            if (!FileUtil.FileExist(String.valueOf(bookInfo.getBookId()), catalogList.get(position + 1).getId() + ".html")) {
                //				new QryChapterInfoAction(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position + 1).getId(), null).start();
                new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position + 1).getId());
            }
        } else {
            toReadingBookActivity(path, position);
        }
        //		closeLoading();
    }

    void toReadingBookActivity(String path, int position) {
        Intent intent = new Intent(CatalogActivity.this, ReadingBookActivity.class);
        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bookInfo.getBookId()));
        intent.putExtra(DefaultConsts.book_name, String.valueOf(bookInfo.getName()));
        intent.putExtra(DefaultConsts.chapterId_index_i, position);
        path = FileUtil.OnlinePath(String.valueOf(bookInfo.getBookId())) + "toc.ncx";
        Uri url = Uri.parse(path);
        intent.setData(url);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, BookStatus_Enum.ONLINE.getValue());
        intent.putExtra("IsFromCatalogActivity", true);
        startActivity(intent);
        QyreaderPerferencesUtil.getInstance(context, Const.phone_number).setChapterIndex(String.valueOf(bookInfo.getBookId()), position);
        if (position + 1 < catalogList.size()) {
            //			new QryChapterInfoAction(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position + 1).getId(), new EmptyAction()).start();
            new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position + 1).getId());
        }
        if (position - 1 >= 0) {
            //			new QryChapterInfoAction(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position - 1).getId(), new EmptyAction()).start();
            new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bookInfo.getBookId()), catalogList.get(position - 1).getId());
        }
    }

    private class ChapterInfoHandler extends TextHttpResponseHandler {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode > 1000) {
                try {
                    Message msg = Message.obtain();
                    msg.what = 102;
                    Bundle bundle = new Bundle();
                    bundle.putInt("result", statusCode);
                    bundle.putString("message", JSONUtil.getString(responseString));
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            handler.sendEmptyMessage(101);

        }

    }

    class ChapterInfoListener implements ActionListener {

        @Override
        public void OK(Object obj) {
            handler.sendEmptyMessage(101);
        }

        @Override
        public void ERROR(int resultCode, String message) {
            Message msg = Message.obtain();
            msg.what = 102;
            Bundle bundle = new Bundle();
            bundle.putInt("result", resultCode);
            bundle.putString("message", message);
            msg.setData(bundle);
            handler.sendMessage(msg);
        }

        @Override
        public void HTTPERROR(int statusCode) {

        }

    }

    private class Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return dirctorys.size();
        }

        @Override
        public Object getItem(int position) {
            return dirctorys.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            view = LayoutInflater.from(CatalogActivity.this).inflate(R.layout.catalog_list_item, null);
            TextView chapterName = (TextView) view.findViewById(R.id.catalog_listview_item_tv);

            String name = (String) getItem(position);
            chapterName.setText(name);
            return view;
        }

    }

    private void initData() {
        myAdapter = new Adapter();
        bookInfo = (BookInfo) getIntent().getSerializableExtra("BookInfo");
        catalogList = new ArrayList<TOCItem>();
        dirctorys = new ArrayList<String>();
        if (FileUtil.FileExist(String.valueOf(bookInfo.getBookId()), FileUtil.Book_CATALOGUE)) {
            initDirctory();
            myAdapter.notifyDataSetChanged();
        } else {
            downloadDirecoty(bookInfo.getNcxUrl());
        }
    }

    private void initDirctory() {
        String dirctory = "";
        if (new File(FileUtil.DownloadPath() + bookInfo.getBookId() + ".ceb").exists()) {
            bookStatus = 3;
        }
        dirctory = FileUtil.OnlinePath(String.valueOf(bookInfo.getBookId())) + FileUtil.Book_CATALOGUE;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            parser = factory.newSAXParser();
            InputStream is = new FileInputStream(new File(dirctory));
            NCXHandler handle = new NCXHandler();
            parser.parse(is, handle);
            is.close();
            dirctorys = handle.getNavLabels();
            catalogList = handle.getNavPointList();
//			addBooktoShelf(bookStatus);
        } catch (IOException | SAXException | ParserConfigurationException e) {
            e.printStackTrace();
        }

    }

    void downloadDirecoty(String url) {
        new DownloadForProgressAction(this, url, FileUtil.OnlinePath(String.valueOf(bookInfo.getBookId())) + FileUtil.Book_CATALOGUE, new DirecotryProgress()).start();
    }

    class DirecotryProgress implements IoTaskProgress {

        @Override
        public void createProgress(HttpType httpType, TaskProgressType type, long max) {

        }

        @Override
        public void updateProgress(HttpType httpType, TaskProgressType type, long increase, long max) {

        }

        @Override
        public void finishProgress(HttpType httpType, TaskProgressType type) {
            handler.sendEmptyMessage(100);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                onBackPressed();
                break;
            default:
                break;
        }
    }

}
